const nodemailer = require('nodemailer')
const { ApiError } = require('./error')

class Mailer {
  constructor(config) {
    this.config = config
    this.transporter = nodemailer.createTransport({
      host: config.mailerHost,
      port: config.mailerPort,
      secure: config.mailerPort === '465',
      auth: {
        user: config.mailerUser,
        pass: config.mailerPass
      }
    })
  }

  // 发送测试邮件
  async sendTestMail() {
    try {
      await this.transporter.verify()
      
      const info = await this.transporter.sendMail({
        from: this.config.mailerFrom || this.config.mailerUser,
        to: this.config.mailerUser,
        subject: '邮件服务测试',
        text: '如果您收到这封邮件，说明邮件服务配置正确。',
        html: `
          <div style="padding: 20px; background-color: #f8f9fa; border-radius: 5px;">
            <h3 style="color: #2c3e50; margin-bottom: 20px;">邮件服务测试</h3>
            <p style="color: #34495e; line-height: 1.6;">
              如果您收到这封邮件，说明邮件服务配置正确。<br>
              这是一封自动发送的测试邮件，无需回复。
            </p>
            <div style="margin-top: 30px; padding-top: 20px; border-top: 1px solid #eee; color: #7f8c8d; font-size: 13px;">
              发送时间：${new Date().toLocaleString()}
            </div>
          </div>
        `
      })

      return info
    } catch (error) {
      throw new ApiError(500, `邮件发送失败: ${error.message}`)
    }
  }
}

module.exports = Mailer 